import {
  selectPhoto,
  savePhoto
} from '../../utils/util'
// 系统信息
const sys = wx.getSystemInfoSync()
// 画布上下文
let preCtx = null
// 图片原始路径和大小
let originPath = ''
// 当前展示的图片实际大小
// 裁剪后还可以继续裁剪
let imageWidth = 0
let imageHeight = 0


// 以下为裁剪框缩放时临时变量
// 当前操作的缩放角
let activeCorner = ''
// 裁剪框缩放前的位置信息
let clipBoxBeforeScaleClipX = 0
let clipBoxBeforeScaleClipY = 0
// 裁剪框缩放前的宽高
let clipBoxBeforeScaleWidth = 0
let clipBoxBeforeScaleHeight = 0
// 裁剪框缩放前点击鼠标的Page(X|Y)位置信息
let clipBoxBeforeScalePageX = 0
let clipBoxBeforeScalePageY = 0

// 以下为裁剪框移动时临时变量
// 裁剪框移动鼠标内部位置信息
let clipBoxMoveInnerX = 0
let clipBoxMoveInnerY = 0

// 图片在窗口面板尺寸小的缩放比
let xScale = 1
let yScale = 1
Page({
  data: {
    // 当前图片路径
    imagePath: '',

    originWidth: 0,
    originHeight: 0,

    // 图片显示面板宽高
    panelWidth: 0,
    panelHeight: 0,

    // 裁剪区域宽高
    clipWidth: 0,
    clipHeight: 0,
    // 裁剪区域位置信息
    clipX: 0,
    clipY: 0,
    // 裁剪区域底图位置信息
    clipImgX: 0,
    clipImgY: 0,

    // 正要裁剪的宽高
    croppingImageWidth: 0,
    croppingImageHeight: 0,
  },
  onLoad() {},
  onReady() {
    this.init()
  },
  //用户点击右上角分享给好友，要现在分享到好友这个设置menu的两个参数，才可以实现分享到朋友圈
  onShareAppMessage:function(){
    wx.showShareMenu({
      withShareTicket:true,
      menu:['shareAppMessage','shareTimeline']
    })
 
    return {
      title:'砖客积木画',
     
      imageUrl:''
    }
  },
    //用户点击右上角分享朋友圈
    onShareTimeline:function(){
      return {
        title:'砖客积木画',
        query:{
          key:value
        },
        imageUrl:'分享时图片底图'
      }
    },
  init() {
    preCtx = wx.createCanvasContext('main')
  },
  ImageCompres(originPath) {
    let that = this
    console.log(originPath)
    wx.getImageInfo({
      src: originPath,
      success(res) {
        //压缩比例,高大于500压缩为500，小于500不压缩        
        let width = res.width;
        let height = res.height;
        if (height < 500) {
          height = height;
        } else {
          width = width * (500 / height);
          height = 500;
        }
        console.log(height,width);
        wx.compressImage({
          src: originPath,
          quality: 20, //压缩质量
          compressedWidth: width, //压缩后宽
          compressedHeight: height, //压缩后高
          success(res){
            originPath = res.tempFilePath;
            console.log(originPath);
           originPath && that.loadImage(originPath) 
           console.log(originPath);
          },
          fail: (err) => {
            console.error(err);
          }
        })
        // originPath && that.loadImage(originPath)
      }
    })
  },

  syscImagePath(event) {
    let that = this
    console.log('event', event);
    originPath = event.detail.value;

    that.ImageCompres(originPath);
  },
  changeImage() {
    if (!this.data.imagePath) {
      return
    }
    selectPhoto((fileRes) => {
      const tempFiles = fileRes.tempFiles[0]

      console.log(tempFiles)
      originPath = tempFiles.tempFilePath || tempFiles.path
      wx.hideLoading()
      originPath && this.loadImage(originPath)
    })
  },
  loadImage(originPath) {
    wx.getImageInfo({
      src: originPath,
      success: async (imgInfo) => {
        this.setData({
          originWidth: imgInfo.width,
          originHeight: imgInfo.height
        })
        this.initImage(imgInfo.width, imgInfo.height, originPath)
      },
      fail: (err) => {
        console.log('getImageInfo', err)
      }
    })
  },

  
  initImage(imgWidth, imgHeight, imagePath) {
    // let that = this;
    console.log('imgWidth',imgWidth)
    console.log('imgHeight',imgHeight)
    console.log('imagePath',imagePath)

    this.setData({
      clipX: 0,
      clipY: 0,
      clipImgX: 0,
      clipImgY: 0
    })

    // 初始化图片，根据窗口大小，设置图片面板尺寸
    let panelH,panelW;
    if (imgHeight < 350 && imgWidth < 350) {
      panelH = 350;
      panelW = 350;
    } else {

      if (imgWidth >= imgHeight) {
         panelW = 350;
         panelH = imgHeight * 350 / imgWidth;

      } else {
        panelH = 500;
        panelW = imgWidth * 500 / imgHeight;
      }
    }
    // console.log(panelH, panelW)

    imageWidth = panelW
    imageHeight = panelH
    xScale = Math.abs(panelW / imgWidth) 
    yScale =  Math.abs(panelH / imgHeight)
    //剪裁框固定
    let clipW = 0;
    if(panelH > panelW){
       clipW = panelW;
    }else{
      clipW = panelH;
    }
    console.log("clipW",clipW);
    console.log("panelW",panelW,panelH);

    this.setData({
      imagePath,
      panelWidth: panelW,
      panelHeight: panelH, //panelH
      clipWidth: clipW,
      clipHeight: clipW, //panelH
      croppingImageWidth: imgWidth,
      croppingImageHeight: imgHeight //imgHeight
    })
  },
  touchstartM(event) {
    const {
      clipX,
      clipY
    } = this.data
    const {
      pageX,
      pageY
    } = event.touches[0]
    // 获取鼠标点在裁剪框的内部位置信息
    clipBoxMoveInnerX = pageX - clipX
    clipBoxMoveInnerY = pageY - clipY
  },
  touchmoveM(event) {
    const {
      pageX,
      pageY
    } = event.touches[0]
    const {
      panelWidth,
      panelHeight,
      clipHeight,
      clipWidth
    } = this.data

    // 裁剪框不能脱离面板
    // X位置范围为 0 到 (面板宽度-裁剪框宽度)
    let clipX = pageX - clipBoxMoveInnerX
    clipX = Math.max(clipX, 0)
    const panelX = panelWidth - clipWidth
    clipX = Math.min(clipX, panelX)
    // Y位置范围为 0 到 (面板高度-裁剪框高度)
    let clipY = pageY - clipBoxMoveInnerY
    clipY = Math.max(clipY, 0)
    const panleY = panelHeight - clipHeight
    clipY = Math.min(clipY, panleY)

    // 裁剪框底图位置信息
    const clipImgX = 0 - clipX
    const clipImgY = 0 - clipY

    this.setData({
      clipX,
      clipY,
      clipImgX,
      clipImgY
    })
  },

  // 处理缩放动作中不同corner时的尺寸位置信息
  getClipX(clipWidth) {
    switch (activeCorner) {
      case 'leftTop':
      case 'leftBottom':
        return clipBoxBeforeScaleClipX + (clipBoxBeforeScaleWidth - clipWidth)
      case 'rightTop':
      case 'rightBottom':
        return clipBoxBeforeScaleClipX;
      default:
        return 0
    }
  },
  getClipY(clipHeight) {
    switch (activeCorner) {
      case 'leftTop':
      case 'rightTop':
        return clipBoxBeforeScaleClipY + (clipBoxBeforeScaleHeight - clipHeight)
      case 'leftBottom':
      case 'rightBottom':
        return clipBoxBeforeScaleClipY
      default:
        return 0
    }
  },
  getScaleXWidthOffset(offsetW) {
    switch (activeCorner) {
      case 'leftTop':
      case 'leftBottom':
        return -offsetW
      case 'rightTop':
      case 'rightBottom':
        return offsetW
      default:
        return 0
    }
  },
  getScaleYHeightOffset(offsetH) {
    switch (activeCorner) {
      case 'rightBottom':
      case 'leftBottom':
        return offsetH
      case 'rightTop':
      case 'leftTop':
        return -offsetH
      default:
        return 0
    }
  },

  touchstart(event) {
    const dragId = event.currentTarget.dataset.id
    const {
      pageX,
      pageY
    } = event.touches[0]
    const {
      clipX,
      clipY,
      clipHeight,
      clipWidth
    } = this.data

    // 设置缩放时临时变量初始化值
    activeCorner = dragId
    clipBoxBeforeScalePageX = pageX
    clipBoxBeforeScalePageY = pageY
    clipBoxBeforeScaleClipX = clipX
    clipBoxBeforeScaleClipY = clipY
    clipBoxBeforeScaleWidth = clipWidth
    clipBoxBeforeScaleHeight = clipHeight
  },
  touchmove(event) {
    const {
      pageX,
      pageY
    } = event.touches[0]
    const {
      panelWidth,
      panelHeight
    } = this.data

    // 缩放在X上的偏移
    const xWidthOffset = this.getScaleXWidthOffset(pageX - clipBoxBeforeScalePageX)
    // 裁剪框最小宽度36
    let clipWidth = Math.max(clipBoxBeforeScaleWidth + xWidthOffset, 36)
    // 设置缩放最大宽度，放大时不能超过面板、缩小时不能超过初始裁剪框
    let tempPanelWidth = pageX > clipBoxBeforeScalePageX ? panelWidth - clipBoxBeforeScaleClipX : clipBoxBeforeScaleWidth + clipBoxBeforeScaleClipX
    // 设置裁剪框宽度
    clipWidth = Math.min(clipWidth, tempPanelWidth)

    // 缩放在Y上的偏移
    const yHeightOffset = this.getScaleYHeightOffset(pageY - clipBoxBeforeScalePageY)
    // 裁剪框最小高度36
    let clipHeight = Math.max(clipBoxBeforeScaleHeight + yHeightOffset, 36)
    // 设置缩放最大高度，放大时不能超过面板、缩小时不能超过初始裁剪框
    let tempPanelHeight = pageY > clipBoxBeforeScalePageY ? panelHeight - clipBoxBeforeScaleClipY : clipBoxBeforeScaleHeight + clipBoxBeforeScaleClipY
    // 设置裁剪框高度
    clipHeight = Math.min(clipHeight, tempPanelHeight)

    // 裁剪框位置信息
    let clipX = this.getClipX(clipWidth)
    let clipY = this.getClipY(clipHeight)
    // 裁剪框底图位置信息
    let clipImgX = 0 - clipX
    let clipImgY = 0 - clipY

    this.setData({
      clipWidth,
      clipHeight,
      clipX,
      clipY,
      clipImgX,
      clipImgY,
      croppingImageWidth: parseInt(clipWidth / xScale),
      croppingImageHeight: parseInt(clipHeight / yScale)
    })
  },
  downloadCanvasImage() {
    console.log(this.data);
    let imgste = wx.getFileSystemManager().readFileSync(this.data.imagePath, "base64");
    wx.showLoading({
      title: '保存中...'
    })
    let that = this;
    wx.request({
      method: "POST",
      url: 'https://www.bricke.cn:8020/add_task/',
      data: {
        openid: wx.getStorageSync('openid'),
        input_photo: imgste
      },
      success(res) {
        console.log(res)
        wx.hideLoading()
        wx.showToast({
          title: "保存成功",
          icon: "success",
        })
        that.data.imagePath = '';

      }
    })
    //savePhoto(imagePath)
  },
  getCropperImage() {
    const {
      imagePath,
      croppingImageWidth,
      croppingImageHeight,
      panelHeight,
      panelWidth,
      clipImgX,
      clipImgY
    } = this.data
    if (!imagePath) {
      return
    };
    console.log("w,h",imageHeight,imageWidth)
    wx.showLoading({
      title: '正在裁剪...'
    })
    preCtx.clearRect(0, 0, imageWidth, imageHeight)

    const width = croppingImageWidth
    const height = croppingImageHeight
    const xPos = Math.abs(clipImgX / xScale)
    const yPos = Math.abs(clipImgY / yScale)
    let newimgSize =  width>height?height:width;
console.log('xPos:',xPos,'yPos:',yPos,'width:',width,'height:',height,"newimgSize",newimgSize)
// preCtx.drawImage(imagePath, xPos, yPos, width, height, 0, 0, width, height)
    preCtx.drawImage(imagePath, xPos, yPos, newimgSize, newimgSize, 0, 0, newimgSize, newimgSize)
    preCtx.save()
    preCtx.restore()

    const that = this
    preCtx.draw(false, function () {
      setTimeout(() => {
        wx.canvasToTempFilePath({
          x: 0,
          y: 0,
          width:newimgSize,
          height:newimgSize,
          destWidth: width,
          destHeight: height,
          canvasId: 'main',
          success: (canRes) => {
            wx.hideLoading()
            that.initImage(newimgSize, newimgSize, canRes.tempFilePath)
          },
          fail(err) {
            wx.hideLoading()
            console.log(err)
          }
        })
      }, 200)
    })
  },
  //恢复原图
  getOriginImage() {
    if (!originPath) {
      return
    }
    const {
      originWidth,
      originHeight
    } = this.data
    this.initImage(originWidth, originHeight, originPath)
  }
})